package com.konsung.ksdc.common.mqtt;

import android.content.Intent;

import com.ibm.mqtt.MqttSimpleCallback;
import com.konsung.ksdc.bean.MqttMsgBean;
import com.konsung.ksdc.common.mqtt.parser.DeleteContactMessageHandler;
import com.konsung.ksdc.common.mqtt.parser.MqttMessageHandler;
import com.konsung.ksdc.common.mqtt.parser.PictureMessageHandler;
import com.konsung.ksdc.common.mqtt.parser.RequestDeleteGroupMessageHandler;
import com.konsung.ksdc.common.mqtt.parser.RequestGroupReceivedMessageHandler;
import com.konsung.ksdc.common.mqtt.parser.RequestPassedMessageHandler;
import com.konsung.ksdc.common.mqtt.parser.RequestReceivedMessageHandler;
import com.konsung.ksdc.common.mqtt.parser.TextMessageHandler;
import com.konsung.ksdc.common.mqtt.parser.VoiceMessageHandler;
import com.konsung.ksdc.common.mqtt.parser.WikiMessageHandler;
import com.konsung.ksdc.common.utils.BroadCastActions;
import com.konsung.ksdc.config.MyApplication;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.service.MqttService;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * mqtt消息处理器
 * Created by andy on 2017/4/19.
 */
public class MqttMessageDispatcher implements MqttSimpleCallback {
    public static final String TAG = "MqttMessageDispatcher";

    private Map<String, MqttMessageHandler> msgHandlers;

    /**
     * 初始化处理器
     */
    public MqttMessageDispatcher() {
        msgHandlers = new HashMap<String, MqttMessageHandler>();
        msgHandlers.put(MqttMessageHandler.MSG_TYPE_TXT, new TextMessageHandler());
        msgHandlers.put(MqttMessageHandler.MSG_TYPE_PIC, new PictureMessageHandler());
        msgHandlers.put(MqttMessageHandler.MSG_TYPE_VOICE, new VoiceMessageHandler());
        msgHandlers.put(MqttMessageHandler.MSG_TYPE_REQUEST_PASSED,
                new RequestPassedMessageHandler());
        msgHandlers.put(MqttMessageHandler.MSG_TYPE_REQUEST_RECEIVED,
                new RequestReceivedMessageHandler());
        msgHandlers.put(MqttMessageHandler.MSG_TYPE_DELETE_CONTACT,
                new DeleteContactMessageHandler());
        msgHandlers.put(MqttMessageHandler.MSG_TYPE_WIKI, new WikiMessageHandler());
        msgHandlers.put(MqttMessageHandler.MSG_TYPE_REQUEST_GROUP, new
                RequestGroupReceivedMessageHandler());
        msgHandlers.put(MqttMessageHandler.MSG_TYPE_DELETE_GROUP, new
                RequestDeleteGroupMessageHandler());
    }

    @Override
    public void connectionLost() throws Exception {
        Intent stopIntent = new Intent(MyApplication.getContext(), MqttService.class);
        MyApplication.getContext().stopService(stopIntent);
        Intent intent = new Intent();
        intent.setAction(BroadCastActions.ACTION_RE_LOGIN);
        MyApplication.getContext().sendBroadcast(intent);
    }

    @Override
    public void publishArrived(String topicName, byte[] bytes, int i, boolean b) throws Exception {
        if (bytes == null || bytes.length == 0) {
            return;
        }

        // 取数组第一位，即消息类型
        String msgType = new String(Arrays.copyOf(bytes, 1));
        MqttMessageHandler handler = msgHandlers.get(msgType);
        if (handler == null) {
            // 消息非法，已忽略
            return;
        }

        // 如果是当前用户在群里发言，则本人也会收到自己发出去的消息，因此屏蔽，不做处理。
        MqttMsgBean msg = handler.fillMsgBeanHeader(topicName, bytes);
        if (!msg.getTopicName().equals(NetConfig.currentUser.getUserName())
                && msg.getContact().equals(NetConfig.currentUser.getUserId())) {
            return;
        }
        handler.hanlderReceivedMessage(topicName, bytes);
    }

    /**
     * 发送消息
     * @param client 客户端
     * @param userId 用户ID
     * @param mqttMsg 消息对象
     * @throws Exception 异常信息
     */
    public void publish(KsdcMqttClient client, String userId, MqttMsgBean mqttMsg)
            throws Exception {

        MqttMessageHandler handler = msgHandlers.get(mqttMsg.getMsgType());
        if (handler == null) {
            // 消息非法，已忽略
            return;
        }

        // 写入消息提醒
        if (MqttMsgUtils.MSG_TARGET_TYPE_PERSONAL.equals(mqttMsg.getMsgTargetType())) {
            handler.writeNotice(userId, "Y", mqttMsg);
        } else {
            handler.writeNotice(mqttMsg.getTopicName(), "Y", mqttMsg);
        }

        Intent intent = new Intent();
        intent.setAction(BroadCastActions.ACTION_MESSAGE_PUBLISHED);
        MyApplication.getContext().sendBroadcast(intent);

        byte[] datas = handler.parseMessage(mqttMsg);
        client.publish(mqttMsg.getTopicName(), datas, KsdcMqttClient.QOS_AR, false);
    }
}
